<template>
	<view class="content">
		<!-- 按钮 -->
		<!-- <view class="contentButton">
			<view style="margin: 0 20rpx;">
				<u-icon name="reload" @click="getList" size="28"></u-icon>
			</view>

		</view> -->
		<!-- 列表 -->
		<u-list @scrolltolower="scrolltolower" @scroll="onscroll" :scrollTop="scrollTop">
			<u-checkbox-group v-model="checkboxValue1" placement="column" @change="checkboxChange">
				<u-list-item :key="index" v-for="(item,index) in ReportList">
					<uni-card :is-shadow="true">
						<!-- <u-row customStyle="margin-bottom: 10px">
							<u-checkbox :customStyle="{marginBottom: '8px'}" :key="item.taskId" label=" "
								:name="item.taskId">
							</u-checkbox>
						</u-row> -->
						<u-row customStyle="margin-bottom: 10px">
							<u-col span="4">
								<view class="demo-layout bg-purple-light">项目编号</view>
							</u-col>
							<u-col span="8">
								<view class="demo-layout ">{{item.reportCode?item.reportCode:''}}</view>
							</u-col>
						</u-row>
						<u-row customStyle="margin-bottom: 10px">
							<u-col span="4">
								<view class="demo-layout bg-purple-light">项目状态</view>
							</u-col>
							<!-- <u-col span="2"> -->
							<view class="demo-layout ">
								<u-tag text="未开启" plain size="mini" type="info" v-if="item.reportStatus==0"></u-tag>
								<u-tag text="开启" plain size="mini" type="success" v-if="item.reportStatus==1"></u-tag>
								<u-tag text="结束" plain size="mini" type="error" v-if="item.reportStatus==2"></u-tag>
							</view>
							<!-- </u-col> -->
						</u-row>
						<u-row customStyle="margin-bottom: 10px">
							<u-col span="4">
								<view class="demo-layout bg-purple-light">项目名称</view>
							</u-col>
							<u-col span="8">
								<view class="demo-layout ">{{item.reportName?item.reportName:''}}</view>
							</u-col>
						</u-row>
						<u-row customStyle="margin-bottom: 10px">
							<u-col span="4">
								<view class="demo-layout bg-purple-light">发起人</view>
							</u-col>
							<u-col span="8">
								<view class="demo-layout ">{{item.reportUserName?item.reportUserName:''}}</view>
							</u-col>
						</u-row>
						<u-row customStyle="margin-bottom: 10px">
							<u-col span="4">
								<view class="demo-layout bg-purple-light">发送日期</view>
							</u-col>
							<u-col span="8">
								<view class="demo-layout ">{{item.reportStartTime?item.reportStartTime:''}}</view>
							</u-col>
						</u-row>
						<u-row customStyle="margin-bottom: 10px">
							<u-col span="4">
								<view class="demo-layout bg-purple-light">截止日期</view>
							</u-col>
							<u-col span="8">
								<view class="demo-layout ">{{item.reportEndTime?item.reportEndTime:''}}</view>
							</u-col>
						</u-row>
						<u-row customStyle="margin-bottom: 10px">
							<u-col span="4">
								<view class="demo-layout bg-purple-light">总数</view>
							</u-col>
							<u-col span="8">
								<view class="demo-layout ">{{item.reportCount}}</view>
							</u-col>
						</u-row>
						<u-row customStyle="margin-bottom: 10px">
							<u-col span="4">
								<view class="demo-layout bg-purple-light">完成数</view>
							</u-col>
							<u-col span="8">
								<view class="demo-layout ">{{item.reportEnd}}</view>
							</u-col>
						</u-row>
						<u-row customStyle="margin-bottom: 10px">
							<u-col span="4">
								<view class="demo-layout bg-purple-light">完成率</view>
							</u-col>
							<u-col span="8">
								<view class="demo-layout ">{{item.reportRate?item.reportRate:''}}</view>
							</u-col>
						</u-row>
						<u-row customStyle="margin-bottom: 10px">
							<u-col span="4">
								<view class="demo-layout bg-purple-light">报告下载</view>
							</u-col>
							<u-col span="8">
								<view class="demo-layout " style="width:90rpx;"><u-tag text="下载" plain size="mini"
										type="primary" @click="download(item)"></u-tag></view>
							</u-col>
						</u-row>
						<!-- <u-row customStyle="margin-bottom: 10px">
							<u-col span="4">
								<view class="demo-layout bg-purple-light">图片下载</view>
							</u-col>
							<u-col span="8">
								<view class="demo-layout " style="width:90rpx;"><u-tag text="下载" plain size="mini" type="primary" ></u-tag></view>
							</u-col>
						</u-row> -->
						<!-- <u-row customStyle="margin-bottom: 10px">
							<u-col span="4">
								<view class="demo-layout bg-purple-light">创建时间</view>
							</u-col>
							<u-col span="8">
								<view class="demo-layout ">{{item.createTime}}</view>
							</u-col>
						</u-row> -->
					</uni-card>
					<!-- </u-cell> -->
				</u-list-item>
				<u-empty mode="list" marginTop="200" v-if="ReportList.length==0">
				</u-empty>
			</u-checkbox-group>
		</u-list>
<!-- 		<l-pagination v-model="queryParams.pageNum" :total="total" :page-size="queryParams.pageSize" :pager-count="5"
			@change="changes" /> -->
		<!-- 新增、修改模态框 -->
		<u-modal :show="show" :title="title" @confirm="confirm" @cancel="cancel" showCancelButton="true">
			<u--form labelPosition="left" :model="model1" :rules="rules" ref="uForm" :labelWidth='90'>
				<u-form-item label="用户昵称" prop="userInfo.nickName" borderBottom ref="item1">
					<u--input v-model="model1.userInfo.nickName" border="none"></u--input>
				</u-form-item>
				<u-form-item label="账号" prop="userInfo.userName" borderBottom ref="item1">
					<u--input v-model="model1.userInfo.userName" border="none"></u--input>
				</u-form-item>
				<u-form-item label="用户密码" prop="userInfo.password" borderBottom ref="item1">
					<u--input v-model="model1.userInfo.password" border="none"></u--input>
				</u-form-item>
				<u-form-item label="任务数量" prop="userInfo.number" borderBottom ref="item1">
					<u--input v-model="model1.userInfo.number" border="none"></u--input>
				</u-form-item>
				<u-form-item label="发送次数" prop="userInfo.sendCount" borderBottom ref="item1">
					<u--input v-model="model1.userInfo.sendCount" border="none"></u--input>
				</u-form-item>
				<u-form-item label="状态" prop="userInfo.status" borderBottom ref="item1">
					<u-radio-group v-model="radiovalue1" placement="row" @change="groupChange">
						<u-radio :customStyle="{marginBottom: '8px'}" v-for="(item, index) in radiolist1" :key="index"
							:label="item.name" :name="item.name" @change="radioChange">
						</u-radio>
					</u-radio-group>
				</u-form-item>
			</u--form>
		</u-modal>
		<!-- 删除模态框 -->
		<u-modal :show="showDetle" title="删除提示" :content='content' @confirm="confirmDetle" @cancel="cancelDetle"
			showCancelButton="true"></u-modal>
		<!-- 创建项目名称对话框 -->
		<u-modal :show="showProjectNameDialog" title="创建项目名称" @confirm="confirmProjectName"
			@cancel="showProjectNameDialog = false">
			<u--input v-model="projectName" placeholder="请输入项目名称"></u--input>
		</u-modal>

		<!-- 发送日期选择对话框 -->
		<u-modal :show="showSendDateDialog" title="选择发送日期" @confirm="confirmSendDate"
			@cancel="showSendDateDialog = false">
			<view class="send-type-select">
				<view style="margin-bottom: 15px;">
					<u-radio-group v-model="sendType" placement="row">
						<u-radio :name="'immediate'" label="立即发送"></u-radio>
						<u-radio :name="'scheduled'" label="选择日期发送"></u-radio>
					</u-radio-group>
				</view>
				<view>
					<uni-datetime-picker type="date" :clear-icon="false" v-if="sendType === 'scheduled'"
						v-model="selectedSendDate" />
				</view>
				<!-- <u-date-picker v-if="sendType === 'scheduled'" v-model="selectedSendDate" mode="date"
					:start-date="new Date().toISOString().split('T')[0]" title="选择发送日期"></u-date-picker> -->

			</view>
		</u-modal>

		<!-- 截止日期选择对话框 -->
		<u-modal :show="showDeadlineDialog" title="选择截止日期" @confirm="confirmDeadline"
			@cancel="showDeadlineDialog = false">
			<!-- <u-date-picker v-model="selectedDeadline" mode="date" :start-date="new Date().toISOString().split('T')[0]"
				title="选择截止日期"></u-date-picker> -->
			<view>
				<uni-datetime-picker type="date" :clear-icon="false" v-model="selectedDeadline" />
			</view>
		</u-modal>

		<!-- 最终确认对话框 -->
		<u-modal :show="showConfirmDialog" title="发送确认" @confirm="finalConfirmSend" @cancel="showConfirmDialog = false">
			<view class="confirm-message">{{ confirmMessage }}</view>
		</u-modal>
		<!-- 加载 -->
		<u-loading-page :loading="showLoading"></u-loading-page>
		<u-back-top :scroll-top="innerScrollTop" top="100" @click="changes"></u-back-top>
		<tabBar selectedIndex=3 v-if="storage_data=='create'"></tabBar>
		<tabBar selectedIndex=1 v-else></tabBar>
	</view>
</template>

<script>
	import {
		listReport,
		exportProject
	} from '@/api/system/bgqd.js'
	import {
		getToken
	} from '@/utils/auth'
	export default {
		data() {
			return {
				indexList: [],
				urls: [
					"https://uviewui.com/album/1.jpg",
					"https://uviewui.com/album/2.jpg",
					"https://uviewui.com/album/3.jpg",
					"https://uviewui.com/album/4.jpg",
					"https://uviewui.com/album/5.jpg",
					"https://uviewui.com/album/6.jpg",
					"https://uviewui.com/album/7.jpg",
					"https://uviewui.com/album/8.jpg",
					"https://uviewui.com/album/9.jpg",
					"https://uviewui.com/album/10.jpg",
				],
				show: false,
				title: '标题',
				content: '是否删除选中数据',
				showSex: false,
				model1: {
					userInfo: {
						name: 'uView UI',
						sex: '',
					},
				},
				actions: [{
						name: '男',
					},
					{
						name: '女',
					},
					{
						name: '保密',
					},
				],
				rules: {
					'userInfo.name': {
						type: 'string',
						required: true,
						message: '请填写姓名',
						trigger: ['blur', 'change']
					},
					'userInfo.sex': {
						type: 'string',
						max: 1,
						required: true,
						message: '请选择男或女',
						trigger: ['blur', 'change']
					},
				},
				radio: '',
				switchVal: false,
				// 基本案列数据
				radiolist1: [{
						name: '正常',
						disabled: false
					},
					{
						name: '停用',
						disabled: false
					},
				],
				// u-radio-group的v-model绑定的值如果设置为某个radio的name，就会被默认选中
				radiovalue1: '正常',
				checkboxValue1: [],
				showDetle: false,
				// 查询参数
				queryParams: {
					pageNum: 1,
					pageSize: 999,
					reportName: null,
					reportUserName: null,
					reportStartTime: null,
					reportEndTime: null,
					createTime: null,
				},
				ReportList: [],
				currentPage: 1,
				total: 0,
				showProjectNameDialog: false,
				projectName: '',
				showSendDateDialog: false,
				sendType: 'immediate', // immediate: 立即发送, scheduled: 定时发送
				selectedSendDate: '',
				showDeadlineDialog: false,
				selectedDeadline: '',
				showConfirmDialog: false,
				confirmMessage: '',
				sendCount: 5, // 假设从接口获取的发送次数
				hasSentToday: false, // 今天是否已发送
				showLoading: false,
				scrollTop: 0,
				innerScrollTop: 0,
				storage_data:''
			}
		},
		onLoad() {
			this.loadmore();
		},
		created() {
			this.getList()
			this.storage_data = uni.getStorageSync('storage_data').user_roles[0];
		},
		onReady() {
			uni.hideTabBar() //隐藏导航栏方法
		},
		onShow() {
			this.getList()
		},
		onPullDownRefresh() {
			console.log('refresh');
			this.getList()
			setTimeout(function() {
				uni.stopPullDownRefresh();
			}, 1000);
		},
		methods: {
			download(item) {
				let data = {
					hiddenName: item.reportName,
					hiddenStartTime: item.reportStartTime,
					hiddenEndTime: item.reportEndTime,
					hiddenUserName: item.reportUserName
				}
				uni.request({
					url: 'http://192.168.1.143:8089/hidden/Investigation/exportProject', // 替换为实际接口地址
					method: 'POST',
					data: data,
					header: {

						'authorization': getToken()
					},
					responseType: 'arraybuffer', // 关键：指定响应类型为二进制数组
					success: (res) => {
						// 1. 获取文件系统管理器
						const fs = uni.getFileSystemManager();

						// 2. 定义临时文件路径（建议使用 USER_DATA_PATH，不同平台通用）
						// 注意：文件扩展名需与实际文件类型匹配（如 .pdf, .xlsx 等）
						const filePath = `${uni.env.USER_DATA_PATH}/exported_project.xlsx`;

						// 3. 将二进制数据写入本地文件
						fs.writeFile({
							filePath,
							data: res.data, // 二进制数组数据
							encoding: 'binary', // 必须指定为 binary，否则可能导致文件损坏
							success: () => {
								console.log('文件写入成功，路径：', filePath);

								// 4. 打开文件（支持 PDF、Word、Excel 等常见格式）
								uni.openDocument({
									filePath,
									showMenu: true, // 是否显示分享等菜单（可选）
									success: () => {
										console.log('文件打开成功');
									},
									fail: (err) => {
										console.error('打开文件失败：', err);
									}
								});
							},
							fail: (err) => {
								console.error('写入文件失败：', err);
							}
						});
					},
					fail: (err) => {
						console.error('接口请求失败：', err);
					}
				});

				//下载文件
				// uni.downloadFile({ //只能是GET请求
				// 	url: "http://192.168.1.143:8089/hidden/Investigation/exportProject", //请求地址
				// 	method: 'POST',
				// 	data: data,
				// 	header: {
				// 		'content-type': 'application/x-www-form-urlencoded',
				// 		'authorization': getToken()
				// 	},
				// 	success: (res) => {
				// 		console.log('res11', res)
				// 		// //下载成功
				// 		if (res.statusCode === 200) {
				// 			//保存文件
				// 			uni.openDocument({
				// 				filePath: res.tempFilePath,
				// 				showMenu: true,
				// 				fileType:'xlsx',
				// 				success: (ress) => {
				// 					console.log('打开文档成功');
				// 				},
				// 				fail: (err) => {
				// 					console.log('打开文档失败',err);
				// 					uni.showToast({
				// 						icon: 'none',
				// 						mask: true,
				// 						title: '打开失败',
				// 					});
				// 				}
				// 			})
				// 		}
				// 	},
				// 	fail: (e) => {
				// 		console.log('e11', e)

				// 		uni.showToast({
				// 			title: `文件下载失败` + e,
				// 			icon: "none",
				// 		})
				// 	}
				// });

			},
			changes(e) {
				// console.log('e', e)
				// this.queryParams.pageNum = e
				// this.getList()
				this.scrollTop = this.innerScrollTop
				this.$nextTick(() => {
					this.scrollTop = 0
				})
				uni.pageScrollTo({
					scrollTop: 0,
					duration: 300 // 滚动动画时长，单位ms
				})

			},
			onscroll(e) {
				// console.log('onscroll:', e);
				this.innerScrollTop = e
			},
			getList() {
				let that = this
				that.showLoading = true
				listReport(that.queryParams).then(res => {
					console.log('res', res)
					// setTimeout(() => {
						that.showLoading = false
					// }, 1000)
					that.ReportList = res.rows
					that.total = res.total
					console.log('that.total', that.total)
				})
			},
			checkboxChange(n) {
				console.log('所有选中的数据', n);
			},
			groupChange(n) {
				console.log('groupChange', n);
			},
			radioChange(n) {
				console.log('radioChange', n);
			},
			// 发送按钮点击事件
			handleAdd() {
				// 显示项目名称输入框
				this.showProjectNameDialog = true;
			},

			// 确认项目名称
			confirmProjectName() {
				if (!this.projectName.trim()) {
					uni.showToast({
						title: '请输入项目名称',
						icon: 'none'
					});
					return;
				}

				sendTask({
					name: this.projectName,
					taskIds: this.checkboxValue1,
					type: '0'
				}).then(res => {
					if (res.code == 200) {
						this.showProjectNameDialog = false;
						this.showSendDateDialog = true;
						// uni.showToast({
						// 	title: '发送成功',
						// 	icon: 'success'
						// });
					}
				})

			},

			// 确认发送日期
			confirmSendDate() {
				if (this.sendType === 'scheduled' && !this.selectedSendDate) {
					uni.showToast({
						title: '请选择发送日期',
						icon: 'none'
					});
					return;
				}
				this.showSendDateDialog = false;
				this.showDeadlineDialog = true;
				// 默认选中今天
				this.selectedDeadline = this.formatDate(new Date());
			},

			// 确认截止日期
			confirmDeadline() {
				if (!this.selectedDeadline) {
					uni.showToast({
						title: '请选择截止日期',
						icon: 'none'
					});
					return;
				}

				// 格式化日期显示
				const sendDateText = this.sendType === 'immediate' ?
					'立即发送' :
					`${this.formatDateText(this.selectedSendDate)}`;

				// 构建确认消息
				this.confirmMessage =
					`本次发送任务${this.checkboxValue1.length}条，任务发送日期${sendDateText}，任务截止日期${this.formatDateText(this.selectedDeadline)}`;
				this.showDeadlineDialog = false;
				this.showConfirmDialog = true;
			},

			// 最终确认发送
			finalConfirmSend() {
				let params = {
					name: this.projectName,
					taskIds: this.checkboxValue1,
					startTime: this.selectedSendDate,
					endTime: this.selectedDeadline,
					type: '1'
				}
				console.log('params', params)
				// 这里实现实际发送逻辑
				uni.showLoading({
					title: '发送中...'
				});
				sendTask({
					name: this.projectName,
					taskIds: this.checkboxValue1,
					startTime: this.selectedSendDate,
					endTime: this.selectedDeadline,
					type: '1'
				}).then(res => {
					if (res.code === 200) {
						this.$modal.closeLoading()
						this.hasSentToday = true;
						this.showConfirmDialog = false;
						this.projectName = '';
						this.selectedSendDate = '';
						this.selectedDeadline = '';
						uni.showToast({
							title: '发送成功',
							icon: 'success'
						});
						// 可以在这里调用刷新列表等操作
						this.getList()
					}
				})
			},

			// 辅助方法：格式化日期
			formatDate(date) {
				const year = date.getFullYear();
				const month = String(date.getMonth() + 1).padStart(2, '0');
				const day = String(date.getDate()).padStart(2, '0');
				return `${year}-${month}-${day}`;
			},

			// 辅助方法：格式化日期显示文本
			formatDateText(dateStr) {
				const date = new Date(dateStr);
				return `${date.getFullYear()}年${date.getMonth() + 1}月${date.getDate()}日`;
			},
			handleUpdate() {
				this.show = true;
				this.title = '修改'
			},
			handleDelete() {
				this.showDetle = true
			},
			confirm() {
				this.show = false;
				console.log('点击确认')
			},
			cancel() {
				this.show = false;
				console.log('点击取消')
			},
			confirmDetle() {
				this.showDetle = false;
				console.log('点击确认')
			},
			cancelDetle() {
				this.showDetle = false;
				console.log('点击取消')
			},
			scrolltolower() {
				this.loadmore();
			},
			loadmore() {
				// for (let i = 0; i < 30; i++) {
				// 	this.indexList.push({
				// 		url: this.urls[uni.$u.random(0, this.urls.length - 1)],
				// 	});
				// }
				// this.queryParams.pageNum+=this.queryParams.pageNum
				// this.getList()
			},
		},
	}
</script>

<style scoped>
	.contentButton {
		width: 100%;
		display: flex;
		justify-content: flex-end;
		align-items: center;
		padding: 20rpx;
	}

	.custom-style {
		width: 150rpx;
		margin: 0 20rpx;
	}

	.logo {
		height: 200rpx;
		width: 200rpx;
		margin-top: 200rpx;
		margin-left: auto;
		margin-right: auto;
		margin-bottom: 50rpx;
	}

	.text-area {
		display: flex;
		justify-content: center;
	}

	.title {
		font-size: 36rpx;
		color: #8f8f94;
	}

	.send-type-select {
		padding: 10px 0;
	}

	.confirm-message {
		padding: 10px 0;
		line-height: 1.6;
		color: #333;
	}

	.u-tag-wrapper {
		margin: 0 auto;
	}
</style>